package com.buaa.divinationmaster;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.switchmaterial.SwitchMaterial;
import com.buaa.divinationmaster.manager.DatabaseManager;
import com.buaa.divinationmaster.model.DivinationRecord;

import java.util.List;

/**
 * 设置页面
 * 根据需求文档实现主题、动画、通知、数据管理等设置功能
 */
public class SettingsActivity extends AppCompatActivity {
    
    private static final String PREFS_NAME = "divination_settings";
    private static final String KEY_THEME_MODE = "theme_mode";
    private static final String KEY_ANIMATION_ENABLED = "animation_enabled";
    private static final String KEY_NOTIFICATION_ENABLED = "notification_enabled";
    private static final String KEY_SOUND_ENABLED = "sound_enabled";
    
    private Spinner spinnerTheme;
    private SwitchMaterial switchAnimation, switchNotification, switchSound;
    private LinearLayout layoutClearHistory, layoutExportData;
    private TextView tvHistoryCount;
    private SharedPreferences prefs;
    private DatabaseManager databaseManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        
        setupToolbar();
        initViews();
        setupSpinner();
        loadSettings();
        updateHistoryCount();
    }
    
    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("设置");
        }
    }
    
    private void initViews() {
        prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        databaseManager = DatabaseManager.getInstance(this);
        
        spinnerTheme = findViewById(R.id.spinnerTheme);
        switchAnimation = findViewById(R.id.switchAnimation);
        switchNotification = findViewById(R.id.switchNotification);
        switchSound = findViewById(R.id.switchSound);
        layoutClearHistory = findViewById(R.id.layoutClearHistory);
        layoutExportData = findViewById(R.id.layoutExportData);
        tvHistoryCount = findViewById(R.id.tvHistoryCount);
        
        // 设置点击事件
        layoutClearHistory.setOnClickListener(v -> showClearHistoryDialog());
        layoutExportData.setOnClickListener(v -> exportData());
    }
    
    private void setupSpinner() {
        String[] themes = {"深色模式", "浅色模式", "跟随系统"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, themes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTheme.setAdapter(adapter);
        
        // 主题切换监听
        spinnerTheme.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                saveThemeMode(position);
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        
        // 动画开关监听
        switchAnimation.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(KEY_ANIMATION_ENABLED, isChecked).apply();
            Toast.makeText(this, isChecked ? "动画效果已开启" : "动画效果已关闭", Toast.LENGTH_SHORT).show();
        });
        
        // 通知开关监听
        switchNotification.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(KEY_NOTIFICATION_ENABLED, isChecked).apply();
            Toast.makeText(this, isChecked ? "推送通知已开启" : "推送通知已关闭", Toast.LENGTH_SHORT).show();
        });
        
        // 音效开关监听
        switchSound.setOnCheckedChangeListener((buttonView, isChecked) -> {
            prefs.edit().putBoolean(KEY_SOUND_ENABLED, isChecked).apply();
            Toast.makeText(this, isChecked ? "音效反馈已开启" : "音效反馈已关闭", Toast.LENGTH_SHORT).show();
        });
    }
    
    private void loadSettings() {
        // 加载主题设置
        int themeMode = prefs.getInt(KEY_THEME_MODE, 0);
        spinnerTheme.setSelection(themeMode);
        
        // 加载开关设置
        switchAnimation.setChecked(prefs.getBoolean(KEY_ANIMATION_ENABLED, true));
        switchNotification.setChecked(prefs.getBoolean(KEY_NOTIFICATION_ENABLED, true));
        switchSound.setChecked(prefs.getBoolean(KEY_SOUND_ENABLED, true));
    }
    
    private void saveThemeMode(int mode) {
        prefs.edit().putInt(KEY_THEME_MODE, mode).apply();
        String[] themes = {"跟随系统", "浅色模式", "深色模式"};
        if (mode < themes.length) {
            Toast.makeText(this, "已切换到" + themes[mode], Toast.LENGTH_SHORT).show();
        }
    }
    
    private void updateHistoryCount() {
        databaseManager.getRecordCount(new DatabaseManager.OnDataCallback<Integer>() {
            @Override
            public void onSuccess(Integer count) {
                runOnUiThread(() -> {
                    tvHistoryCount.setText("(" + count + " 条记录)");
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    tvHistoryCount.setText("(获取失败)");
                });
            }
        });
    }
    
    private void showClearHistoryDialog() {
        new AlertDialog.Builder(this)
            .setTitle("清除历史记录")
            .setMessage("确定要清除所有历史记录吗？此操作不可撤销。")
            .setPositiveButton("清除", (dialog, which) -> clearHistory())
            .setNegativeButton("取消", null)
            .show();
    }
    
    private void clearHistory() {
        databaseManager.clearAllRecords(new DatabaseManager.OnDataCallback<Void>() {
            @Override
            public void onSuccess(Void data) {
                runOnUiThread(() -> {
                    Toast.makeText(SettingsActivity.this, "历史记录已清除", Toast.LENGTH_SHORT).show();
                    updateHistoryCount();
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    Toast.makeText(SettingsActivity.this, "清除失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    private void exportData() {
        new AlertDialog.Builder(this)
            .setTitle("导出数据")
            .setMessage("选择要导出的数据格式：")
            .setPositiveButton("文本格式", (dialog, which) -> exportAsText())
            .setNegativeButton("JSON格式", (dialog, which) -> exportAsJson())
            .setNeutralButton("取消", null)
            .show();
    }
    
    private void exportAsText() {
        databaseManager.getAllRecords(new DatabaseManager.OnDataCallback<List<DivinationRecord>>() {
            @Override
            public void onSuccess(List<DivinationRecord> records) {
                runOnUiThread(() -> {
                    if (records.isEmpty()) {
                        Toast.makeText(SettingsActivity.this, "没有可导出的数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    StringBuilder exportText = new StringBuilder();
                    exportText.append("【占卜大师 - 数据导出】\n");
                    exportText.append("导出时间：").append(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(new java.util.Date())).append("\n");
                    exportText.append("总记录数：").append(records.size()).append("\n\n");
                    
                    for (DivinationRecord record : records) {
                        exportText.append("===================\n");
                        exportText.append("占卜类型：").append(record.getTypeDisplayName()).append("\n");
                        exportText.append("占卜时间：").append(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault()).format(new java.util.Date(record.getTimestamp()))).append("\n");
                        exportText.append("占卜问题：").append(record.getQuestion()).append("\n");
                        exportText.append("解读结果：\n").append(record.getInterpretation()).append("\n");
                        if (record.isFavorite()) {
                            exportText.append("★ 已收藏\n");
                        }
                        exportText.append("\n");
                    }
                    
                    shareExportedData(exportText.toString(), "占卜记录导出.txt");
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    Toast.makeText(SettingsActivity.this, "导出失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    private void exportAsJson() {
        databaseManager.getAllRecords(new DatabaseManager.OnDataCallback<List<DivinationRecord>>() {
            @Override
            public void onSuccess(List<DivinationRecord> records) {
                runOnUiThread(() -> {
                    if (records.isEmpty()) {
                        Toast.makeText(SettingsActivity.this, "没有可导出的数据", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    try {
                        // 简化的JSON导出（实际项目中可使用Gson或其他JSON库）
                        StringBuilder json = new StringBuilder();
                        json.append("{\n");
                        json.append("  \"export_info\": {\n");
                        json.append("    \"app_name\": \"占卜大师\",\n");
                        json.append("    \"export_time\": \"").append(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(new java.util.Date())).append("\",\n");
                        json.append("    \"total_records\": ").append(records.size()).append("\n");
                        json.append("  },\n");
                        json.append("  \"records\": [\n");
                        
                        for (int i = 0; i < records.size(); i++) {
                            DivinationRecord record = records.get(i);
                            json.append("    {\n");
                            json.append("      \"id\": ").append(record.getId()).append(",\n");
                            json.append("      \"type\": \"").append(record.getType()).append("\",\n");
                            json.append("      \"question\": \"").append(record.getQuestion().replace("\"", "\\\"")).append("\",\n");
                            json.append("      \"interpretation\": \"").append(record.getInterpretation().replace("\"", "\\\"").replace("\n", "\\n")).append("\",\n");
                            json.append("      \"timestamp\": ").append(record.getTimestamp()).append(",\n");
                            json.append("      \"is_favorite\": ").append(record.isFavorite()).append("\n");
                            json.append("    }");
                            if (i < records.size() - 1) json.append(",");
                            json.append("\n");
                        }
                        
                        json.append("  ]\n");
                        json.append("}");
                        
                        shareExportedData(json.toString(), "占卜记录导出.json");
                        
                    } catch (Exception e) {
                        Toast.makeText(SettingsActivity.this, "JSON导出失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
            
            @Override
            public void onError(Exception error) {
                runOnUiThread(() -> {
                    Toast.makeText(SettingsActivity.this, "导出失败：" + error.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    private void shareExportedData(String content, String filename) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, content);
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "占卜大师数据导出 - " + filename);
        
        startActivity(Intent.createChooser(shareIntent, "导出数据"));
        Toast.makeText(this, "数据导出完成", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
